<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { useProductStore } from '@/stores/productStore'
import { useUserStore } from '@/stores/userStore'
import { useOrderStore } from '@/stores/orderStore'

const productStore = useProductStore()
const userStore = useUserStore()
const orderStore = useOrderStore()

const barChartRef = ref(null)
const pieChartRef = ref(null)
let barChart = null
let pieChart = null

// 统计数据
const statistics = ref({
  totalUsers: 0,
  totalProducts: 0,
  totalOrders: 0,
  totalAmount: 0
})

// 获取所有数据
const fetchAllData = async () => {
  try {
    // 获取商品分类数据
    const categoryData = await productStore.fetchCategoryData()
    console.log('商品分类数据:', categoryData)
    initBarChart(categoryData)//传递个柱状图
    
    // 获取订单数据
    const orders = await orderStore.fetchOrders()
    // console.log('订单数据:', orders)
    statistics.value.totalOrders = orders.length
    //从0开始累加，callback(accumulator, currentValue, currentIndex, array)
    // statistics.value.totalAmount = orders.reduce((sum, order) => sum + order.amount, 0)
    statistics.value.totalAmount = orders.reduce((sum, order) => sum + Number(order.amount), 0)
    // 计算订单状态分布
    const orderStatus = orders.reduce((sum, order) => {
      // 统计不同状态的订单数量
      if (order.status === 'pending') {
        sum.pending = (sum.pending || 0) + 1//保证它的初始值是0
      } else if (order.status === 'completed') {
        sum.completed = (sum.completed || 0) + 1
      }
      return sum
      //order 是 { status: 'pending' }，此时 sum = {} -》 sum = { pending: 1 }
    }, {})
    console.log('订单状态分布:', orderStatus)
    initPieChart(orderStatus)

    // 获取用户和商品总数
    const users = await userStore.fetchUsers()
    const products = await productStore.fetchProducts()
    statistics.value.totalUsers = users.length
    statistics.value.totalProducts = products.length
  } catch (error) {
    // console.error('获取数据失败:', error)
  }
}

// 初始化柱状图
const initBarChart = (data) => {
  if (barChartRef.value) {
    barChart = echarts.init(barChartRef.value)
    const option = {
      title: {
        text: '商品类别统计',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: data.xAxisData
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: data.seriesData ,
        type: 'bar',
      }]
    }
    barChart.setOption(option)
  }
}
const initPieChart = (statusData) => {
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
    const option = {
      title: {
        text: '订单状态分布',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        type: 'pie',
        radius: '50%',
        data: [
          {value: statusData['pending'], name: '待处理'},
          {value: statusData['completed'], name: '已完成'}
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    pieChart.setOption(option)
  }
}



onMounted(() => {
  fetchAllData()
})
</script>

<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>总用户数</span>
          </div>
        </template>
        <div class="stat-value">{{ statistics.totalUsers }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>商品总数</span>
          </div>
        </template>
        <div class="stat-value">{{ statistics.totalProducts }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>订单总数</span>
          </div>
        </template>
        <div class="stat-value">{{ statistics.totalOrders }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>总金额</span>
          </div>
        </template>
        <div class="stat-value">¥{{ statistics.totalAmount.toFixed(2) }}</div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-card class="chart-card">
        <div ref="barChartRef" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <div ref="pieChartRef" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-card {
  height: 400px;
  margin-bottom: 20px;
}

.chart {
  height: 100%;
  width: 100%;
  min-height: 300px;
}
</style>
